﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Configuration;
using System.Reflection;
using Caculatorlib.Factorys;
using Caculatorlib; 

namespace Caculate_UI
{
    public partial class Form1 : Form
    {
        //两个操作数
        private double dateX;
        private double dateY;
        cl_20190440423_caculate cal = null;
        cl_20190440423_Factory ft;
        
        public Form1()
        {
            InitializeComponent();
        }

       

        private void btnNumbers_Click(object sender, EventArgs e)
        {

            txtInput.Text += ((Button)sender).Text;
            txtResult.Text += ((Button)sender).Text;
        }

        private void btnCalculate_Click(object sender, EventArgs e)
        {
            dateY = Convert.ToDouble(txtInput.Text);
            var result = cal.Calculate(dateX, dateY);

            //结果显示
            txtResult.Text += "=" + result.ToString();
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            txtInput.Text = "";
            txtResult.Text = "";
        }

        private void btnOps_Click(object sender, EventArgs e)
        {
            dateX = double.Parse(txtResult.Text);
            txtInput.Text = "";
            txtResult.Text += ((Button)sender).Text;

            #region 使用配置文件和反射机制，根据所按的操作符来决定实例化什么对象


            //第一步：对于配置文件进行解析，读取配置文件的参数
            Configuration conf = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            string factoryname = conf.AppSettings.Settings[((Button)sender).Text].Value;

            //第二步：通过反射机制实例化对象
            Assembly ass = Assembly.Load("Caculatorlib");
            ft = (cl_20190440423_Factory)ass.CreateInstance(factoryname);

            cal = ft.GetCalculator();
            #endregion
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {

            if (txtInput.Text.Length > 0)
            {
                var str = txtInput.Text.Remove(txtInput.Text.Length - 1, 1);
                txtInput.Text = str;
            }

            if (txtResult.Text.Length > 0)
            {
                var str = txtResult.Text.Remove(txtResult.Text.Length - 1, 1);
                txtResult.Text = str;
            }
        }

        private void txtResult_TextChanged(object sender, EventArgs e)
        {

        }
    }
}
